using System;
using System.Windows.Threading;
using System.Collections.Generic;

namespace Silvery.Loader
{
    /// <summary>
    /// 下载管理器
    /// </summary>
    public sealed class LoaderManager : List<ILoader>, ILoaderManager
    {
        static LoaderManager current;
        public static ILoaderManager Current
        {
            get
            {
                
                if (current == null)
                    current = new LoaderManager();
                return current;
            }
        }
        private LoaderManager()
        {
            DispatcherTimer loop = new DispatcherTimer();
            loop.Interval = TimeSpan.FromSeconds(5);
            loop.Tick += new EventHandler(loop_Tick);
            loop.Start();

            
        }

        void loop_Tick(object sender, EventArgs e)
        {
            ILoader[] array = new ILoader[this.Count];
            this.CopyTo(array);
            
            foreach (var item in array)
            {
                if (item.LaoderState == LaoderState.Error)
                    this.Remove(item);
            }
        }
        /// <summary>
        /// 这个功能暂时没用
        /// </summary>
        public LaodType LaodType
        {
            get;
            set;
        }
        public ILoader Load(ILoader loader)
        {
            var res = ResourceManager.Current.Contains(loader.LoadUri);
            if (res != null)
            {
                loader.Result = res;
                return loader;
            }
            ILoader[] array = new ILoader[this.Count];
            this.CopyTo(array);
            foreach (var item in array)
            {
                var i = Uri.Compare(loader.LoadUri, item.LoadUri, UriComponents.Path, UriFormat.SafeUnescaped, StringComparison.Ordinal);
                if (i == 0)
                {
                    if (item.LaoderState == LaoderState.Completed)
                    {
                        loader.Result = item.Result;                        
                    }
                    else
                        return item;
                }
            }
            this.Add(loader);
            return loader;
        }
        
        public new void Remove(ILoader loader)
        {
            if (base.Contains(loader))
            {
                base.Remove(loader);
                loader.Dispose();
            }
        }
    }
}
